package com.dcits.filter.sensitive;

import com.google.common.collect.ImmutableMap;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SensitiveDataUtils {
    private SensitiveDataUtils() {
    }

    // 默认脱敏规则（可动态扩展）
    private static final Map<String, String> DEFAULT_RULES = ImmutableMap.of(
            "password", "******",                          // 密码直接替换为星号
            "idCard", "(\\d{4})\\d{10}(\\w{4})",           // 身份证保留前后4位
            "phone", "(\\d{3})\\d{4}(\\d{4})",             // 手机号保留前3后4
            "email", "(\\w{3}).*(@.*)"                    // 邮箱保留前3位和域名
    );

    /**
     * 通用脱敏方法
     *
     * @param text        原始文本
     * @param customRules 自定义规则（可选，覆盖默认规则）
     * @return 脱敏后的文本
     */
    public static String desensitize(String text, Map<String, String> customRules) {
        if (text == null || text.isEmpty()) return text;

        // 合并规则（自定义优先）
        Map<String, String> rules = new HashMap<>(DEFAULT_RULES);
        if (customRules != null) rules.putAll(customRules);

        // 处理所有规则
        for (Map.Entry<String, String> entry : rules.entrySet()) {
            String field = entry.getKey();
            String rule = entry.getValue();

            // 正则匹配字段（如 "password":"xxx" 或 password=xxx）
            Pattern fieldPattern = Pattern.compile("(?i)(\"?" + field + "\"?[:=]\"?)(.*?)(\"?[,}\\s])", Pattern.DOTALL);
            Matcher matcher = fieldPattern.matcher(text);
            StringBuffer result = new StringBuffer();

            while (matcher.find()) {
                String originalValue = matcher.group(2);
                String maskedValue = applyRule(originalValue, rule);
                matcher.appendReplacement(result, matcher.group(1) + maskedValue + matcher.group(3));
            }
            matcher.appendTail(result);
            text = result.toString();
        }
        return text;
    }

    // 应用单条脱敏规则
    private static String applyRule(String value, String rule) {
        if (rule.equals("******")) return rule;  // 直接替换
        try {
            // 正则替换（如手机号、身份证）
            return value.replaceAll(rule, "$1****$2");
        } catch (Exception e) {
            // 保留前N位（如 username 保留前3位）
            int keepLength = Integer.parseInt(rule.replaceAll("\\D", ""));
            return value.substring(0, Math.min(keepLength, value.length())) + "****";
        }
    }
}